<!DOCTYPE html>
<html lang="zh-cn">
  <head>
    
    <meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="generator" content="Hugo 0.56.3 with theme Tranquilpeak 0.4.7-BETA">
<meta name="author" content="iFence">
<meta name="keywords" content="">
<meta name="description" content="背景 对于一种完善的编程语言，break和continue功能可以说是刚需，但是当学完scala以后却发现没有这两个关键字，那么scala要如何来实现这两个功能呢？ 虽然没有这两个关键字，但是scala却提供了多种方式满足这一功能， break的实现 首先再明确一下，break的功能就是">


<meta property="og:description" content="背景 对于一种完善的编程语言，break和continue功能可以说是刚需，但是当学完scala以后却发现没有这两个关键字，那么scala要如何来实现这两个功能呢？ 虽然没有这两个关键字，但是scala却提供了多种方式满足这一功能， break的实现 首先再明确一下，break的功能就是">
<meta property="og:type" content="article">
<meta property="og:title" content="Scala中continue和break的几种实现方式">
<meta name="twitter:title" content="Scala中continue和break的几种实现方式">
<meta property="og:url" content="https://ifence.gitee.io/2019/09/scala%E4%B8%ADcontinue%E5%92%8Cbreak%E7%9A%84%E5%87%A0%E7%A7%8D%E5%AE%9E%E7%8E%B0%E6%96%B9%E5%BC%8F/">
<meta property="twitter:url" content="https://ifence.gitee.io/2019/09/scala%E4%B8%ADcontinue%E5%92%8Cbreak%E7%9A%84%E5%87%A0%E7%A7%8D%E5%AE%9E%E7%8E%B0%E6%96%B9%E5%BC%8F/">
<meta property="og:site_name" content="iFence&#39;s Nest">
<meta property="og:description" content="背景 对于一种完善的编程语言，break和continue功能可以说是刚需，但是当学完scala以后却发现没有这两个关键字，那么scala要如何来实现这两个功能呢？ 虽然没有这两个关键字，但是scala却提供了多种方式满足这一功能， break的实现 首先再明确一下，break的功能就是">
<meta name="twitter:description" content="背景 对于一种完善的编程语言，break和continue功能可以说是刚需，但是当学完scala以后却发现没有这两个关键字，那么scala要如何来实现这两个功能呢？ 虽然没有这两个关键字，但是scala却提供了多种方式满足这一功能， break的实现 首先再明确一下，break的功能就是">
<meta property="og:locale" content="zh-cn">

  
    <meta property="article:published_time" content="2019-09-03T11:18:16">
  
  
    <meta property="article:modified_time" content="2019-09-03T11:18:16">
  
  
  
    
      <meta property="article:section" content="scala">
    
  
  
    
      <meta property="article:tag" content="scala">
    
      <meta property="article:tag" content="break和continue">
    
  


<meta name="twitter:card" content="summary">











  <meta property="og:image" content="https://avatars1.githubusercontent.com/u/53120100?s=460&v=4">
  <meta property="twitter:image" content="https://avatars1.githubusercontent.com/u/53120100?s=460&v=4">


    <title>Scala中continue和break的几种实现方式</title>

    <link rel="icon" href="https://ifence.gitee.io/favicon.png">
    

    

    <link rel="canonical" href="https://ifence.gitee.io/2019/09/scala%E4%B8%ADcontinue%E5%92%8Cbreak%E7%9A%84%E5%87%A0%E7%A7%8D%E5%AE%9E%E7%8E%B0%E6%96%B9%E5%BC%8F/">

    
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css" integrity="sha256-eZrrJcwDc/3uDhsdt61sL2oOBY362qM3lon1gyExkL0=" crossorigin="anonymous" />
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/fancybox/2.1.4/jquery.fancybox.min.css" integrity="sha256-vuXZ9LGmmwtjqFX1F+EKin1ThZMub58gKULUyf0qECk=" crossorigin="anonymous" />
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/fancybox/2.1.4/helpers/jquery.fancybox-thumbs.min.css" integrity="sha256-SEa4XYAHihTcEP1f5gARTB2K26Uk8PsndQYHQC1f4jU=" crossorigin="anonymous" />
    
    
    <link rel="stylesheet" href="https://ifence.gitee.io/css/style-twzjdbqhmnnacqs0pwwdzcdbt8yhv8giawvjqjmyfoqnvazl0dalmnhdkvp7.min.css" />
    
    

    
      
<script type="application/javascript">
var doNotTrack = false;
if (!doNotTrack) {
	(function(i,s,o,g,r,a,m){i['GoogleAnalyticsObject']=r;i[r]=i[r]||function(){
	(i[r].q=i[r].q||[]).push(arguments)},i[r].l=1*new Date();a=s.createElement(o),
	m=s.getElementsByTagName(o)[0];a.async=1;a.src=g;m.parentNode.insertBefore(a,m)
	})(window,document,'script','https://www.google-analytics.com/analytics.js','ga');
	ga('create', 'UA-123-45', 'auto');
	
	ga('send', 'pageview');
}
</script>

    
    
  </head>

  <body>
    <div id="blog">
      <header id="header" data-behavior="5">
  <i id="btn-open-sidebar" class="fa fa-lg fa-bars"></i>
  <div class="header-title">
    <a class="header-title-link" href="https://ifence.gitee.io/">iFence&#39;s Nest</a>
  </div>
  
    
      <a class="header-right-picture "
         href="https://ifence.gitee.io/#about">
    
    
    
      
        <img class="header-picture" src="https://avatars1.githubusercontent.com/u/53120100?s=460&amp;v=4" alt="作者的图片" />
      
    
    </a>
  
</header>

      <nav id="sidebar" data-behavior="5">
  <div class="sidebar-container">
    
      <div class="sidebar-profile">
        <a href="https://ifence.gitee.io/#about">
          <img class="sidebar-profile-picture" src="https://avatars1.githubusercontent.com/u/53120100?s=460&amp;v=4" alt="作者的图片" />
        </a>
        <h4 class="sidebar-profile-name">iFence</h4>
        
          <h5 class="sidebar-profile-bio">虽千万人吾往矣</h5>
        
      </div>
    
    <ul class="sidebar-buttons">
      
  <li class="sidebar-button">
    
      <a class="sidebar-button-link " href="https://ifence.gitee.io/">
    
      <i class="sidebar-button-icon fa fa-lg fa-home"></i>
      
      <span class="sidebar-button-desc">首页</span>
    </a>
  </li>

  <li class="sidebar-button">
    
      <a class="sidebar-button-link " href="https://ifence.gitee.io/archives">
    
      <i class="sidebar-button-icon fa fa-lg fa-archive"></i>
      
      <span class="sidebar-button-desc">归档</span>
    </a>
  </li>

  <li class="sidebar-button">
    
      <a class="sidebar-button-link " href="https://ifence.gitee.io/tags">
    
      <i class="sidebar-button-icon fa fa-lg fa-tags"></i>
      
      <span class="sidebar-button-desc">标签</span>
    </a>
  </li>

  <li class="sidebar-button">
    
      <a class="sidebar-button-link " href="https://ifence.gitee.io/categories">
    
      <i class="sidebar-button-icon fa fa-lg fa-bookmark"></i>
      
      <span class="sidebar-button-desc">分类</span>
    </a>
  </li>

  <li class="sidebar-button">
    
      <a class="sidebar-button-link " href="https://ifence.gitee.io/about">
    
      <i class="sidebar-button-icon fa fa-lg fa-user"></i>
      
      <span class="sidebar-button-desc">关于</span>
    </a>
  </li>


    </ul>
    <ul class="sidebar-buttons">
      
  <li class="sidebar-button">
    
      <a class="sidebar-button-link " href="https://github.com/iFence" target="_blank" rel="noopener">
    
      <i class="sidebar-button-icon fa fa-lg fa-github"></i>
      
      <span class="sidebar-button-desc">GitHub</span>
    </a>
  </li>

  <li class="sidebar-button">
    
      <a class="sidebar-button-link " href="https://blog.csdn.net/Vector97" target="_blank" rel="noopener">
    
      <i class="sidebar-button-icon fa fa-lg fa-codiepie"></i>
      
      <span class="sidebar-button-desc">CSDN</span>
    </a>
  </li>

  <li class="sidebar-button">
    
      <a class="sidebar-button-link " href="https://www.jianshu.com/u/424596d51c5a" target="_blank" rel="noopener">
    
      <i class="sidebar-button-icon fa fa-lg fa-gratipay"></i>
      
      <span class="sidebar-button-desc">简书</span>
    </a>
  </li>


    </ul>
    <ul class="sidebar-buttons">
      

    </ul>
  </div>
</nav>

      

      <div id="main" data-behavior="5"
        class="
               hasCoverMetaIn
               ">
        <article class="post" itemscope itemType="http://schema.org/BlogPosting">
          
          
            <div class="post-header main-content-wrap text-left">
  
    <h1 class="post-title" itemprop="headline">
      Scala中continue和break的几种实现方式
    </h1>
  
  
  <div class="postShorten-meta post-meta">
    
      <time itemprop="datePublished" datetime="2019-09-03T11:18:16&#43;08:00">
        
  九月 3, 2019

      </time>
    
    
  
  
    <span>发布在</span>
    
      <a class="category-link" href="https://ifence.gitee.io/categories/scala">scala</a>
    
  

  </div>

</div>
          
          <div class="post-content markdown" itemprop="articleBody">
            <div class="main-content-wrap">
              

<h2 id="背景">背景</h2>

<p>对于一种完善的编程语言，break和continue功能可以说是刚需，但是当学完scala以后却发现没有这两个关键字，那么scala要如何来实现这两个功能呢？</p>

<p>虽然没有这两个关键字，但是scala却提供了多种方式满足这一功能，</p>

<h2 id="break的实现">break的实现</h2>

<p>首先再明确一下，break的功能就是要结束当前的for循环。下面总结了三种方式。</p>

<ol>
<li><p>使用<code>breakable()</code>和<code>break()</code>组合的方式</p>

<pre><code class="language-java">//这个包要引入才能用breakable和break
import util.control.Breaks._
   breakable{
     while (n &lt; 20) {
       print(n + &quot; hello&quot;)
       n += 1
       if (n == 18) {
         break()
       }
       println(&quot;OK&quot;)
     }
   }
</code></pre></li>

<li><p>使用循环守卫的方式</p>

<pre><code class="language-java">//使用循环守卫的方式，编译器会自己判断如果if条件无法再改为true了，就会直接退出
for(i &lt;- 1 to 100 if i &lt; 30){
   println(i)
}
</code></pre></li>

<li><p>使用<code>takeWhile()</code>函数</p>

<pre><code class="language-scala">//takeWhile是一个高阶函数，当不满足条件的时候可以跳出循环
//这种方式与上面第二种方式完全等价，而且只用了一行
(1 to 100).takeWhile(_ &lt; 30).foreach(println)
</code></pre></li>
</ol>

<p>上面三种方式，第一种比较复杂一般能不用尽量不要使用，第二种方式相比第一种更简单，比第三种更容易理解，所以我常用的是第二种。</p>

<h2 id="continue的实现">continue的实现</h2>

<p>与上面break相对应，continue也有两种实现方式。</p>

<ol>
<li><p>breakable和break组合的方式</p>

<pre><code class="language-java">//控制一下breakable的作用范围就可以实现由break功能到continue功能的转变
import util.control.Breaks._
for(i &lt;- 1 to 10){
     breakable{
       if (i == 4) break()
       println(&quot;test &quot;+i)
     }
}
</code></pre></li>

<li><p>循环守卫的方式</p>

<pre><code class="language-java">for(i &lt;- 1 to 10 if(i != 2){
   println(i)//当i等于2的时候就跳过当前循环执行下一次循环
}
</code></pre></li>
</ol>

<p>因为for循环比较灵活，所以笔者实际开发中比较常用的还是循环守卫的方式实现continue和break。</p>

<p><strong>微信公众号：大数据报文</strong></p>

              
            </div>
          </div>
          <div id="post-footer" class="post-footer main-content-wrap">
            
              
                
                
                  <div class="post-footer-tags">
                    <span class="text-color-light text-small">标签</span><br/>
                    
  <a class="tag tag--primary tag--small" href="https://ifence.gitee.io/tags/scala/">scala</a>

  <a class="tag tag--primary tag--small" href="https://ifence.gitee.io/tags/break%E5%92%8Ccontinue/">break和continue</a>

                  </div>
                
              
            
            <div class="post-actions-wrap">
  
      <nav >
        <ul class="post-actions post-action-nav">
          
            <li class="post-action">
              
                <a class="post-action-btn btn btn--default tooltip--top" href="https://ifence.gitee.io/2019/12/pandas/" data-tooltip="pandas">
              
                  <i class="fa fa-angle-left"></i>
                  <span class="hide-xs hide-sm text-small icon-ml">下一篇</span>
                </a>
            </li>
            <li class="post-action">
              
                <a class="post-action-btn btn btn--default tooltip--top" href="https://ifence.gitee.io/2019/08/kafka%E5%88%A0%E9%99%A4%E4%B8%BB%E9%A2%98%E8%AF%A6%E8%A7%A3/" data-tooltip="Kafka删除主题详解">
              
                  <span class="hide-xs hide-sm text-small icon-mr">上一篇</span>
                  <i class="fa fa-angle-right"></i>
                </a>
            </li>
          
        </ul>
      </nav>
    <ul class="post-actions post-action-share" >
      
        <li class="post-action hide-lg hide-md hide-sm">
          <a class="post-action-btn btn btn--default btn-open-shareoptions" href="#btn-open-shareoptions">
            <i class="fa fa-share-alt"></i>
          </a>
        </li>
        
      
      
        <li class="post-action">
          <a class="post-action-btn btn btn--default" href="#disqus_thread">
            <i class="fa fa-comment-o"></i>
          </a>
        </li>
      
      <li class="post-action">
        
          <a class="post-action-btn btn btn--default" href="#">
        
          <i class="fa fa-list"></i>
        </a>
      </li>
    </ul>
  
</div>

            
              
                <div id="disqus_thread">
  <noscript>Please enable JavaScript to view the <a href="//disqus.com/?ref_noscript">comments powered by Disqus.</a></noscript>
</div>
              
            
          </div>
        </article>
        <footer id="footer" class="main-content-wrap">
  <span class="copyrights">
    &copy; 2019 iFence. All Rights Reserved
  </span>
</footer>

      </div>
      <div id="bottom-bar" class="post-bottom-bar" data-behavior="5">
        <div class="post-actions-wrap">
  
      <nav >
        <ul class="post-actions post-action-nav">
          
            <li class="post-action">
              
                <a class="post-action-btn btn btn--default tooltip--top" href="https://ifence.gitee.io/2019/12/pandas/" data-tooltip="pandas">
              
                  <i class="fa fa-angle-left"></i>
                  <span class="hide-xs hide-sm text-small icon-ml">下一篇</span>
                </a>
            </li>
            <li class="post-action">
              
                <a class="post-action-btn btn btn--default tooltip--top" href="https://ifence.gitee.io/2019/08/kafka%E5%88%A0%E9%99%A4%E4%B8%BB%E9%A2%98%E8%AF%A6%E8%A7%A3/" data-tooltip="Kafka删除主题详解">
              
                  <span class="hide-xs hide-sm text-small icon-mr">上一篇</span>
                  <i class="fa fa-angle-right"></i>
                </a>
            </li>
          
        </ul>
      </nav>
    <ul class="post-actions post-action-share" >
      
        <li class="post-action hide-lg hide-md hide-sm">
          <a class="post-action-btn btn btn--default btn-open-shareoptions" href="#btn-open-shareoptions">
            <i class="fa fa-share-alt"></i>
          </a>
        </li>
        
      
      
        <li class="post-action">
          <a class="post-action-btn btn btn--default" href="#disqus_thread">
            <i class="fa fa-comment-o"></i>
          </a>
        </li>
      
      <li class="post-action">
        
          <a class="post-action-btn btn btn--default" href="#">
        
          <i class="fa fa-list"></i>
        </a>
      </li>
    </ul>
  
</div>

      </div>
      <div id="share-options-bar" class="share-options-bar" data-behavior="5">
  <i id="btn-close-shareoptions" class="fa fa-close"></i>
  <ul class="share-options">
    
  </ul>
</div>
<div id="share-options-mask" class="share-options-mask"></div>
    </div>
    
    <div id="about">
  <div id="about-card">
    <div id="about-btn-close">
      <i class="fa fa-remove"></i>
    </div>
    
      <img id="about-card-picture" src="https://avatars1.githubusercontent.com/u/53120100?s=460&amp;v=4" alt="作者的图片" />
    
    <h4 id="about-card-name">iFence</h4>
    
      <div id="about-card-bio">虽千万人吾往矣</div>
    
    
      <div id="about-card-job">
        <i class="fa fa-briefcase"></i>
        <br/>
        大数据开发
      </div>
    
    
      <div id="about-card-location">
        <i class="fa fa-map-marker"></i>
        <br/>
        中国 山东
      </div>
    
  </div>
</div>

    

    
  
    
      <div id="cover" style="background-image:url('https://ifence.gitee.io/images/cover.jpg');"></div>
    
  


    
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.2.4/jquery.min.js" integrity="sha256-BbhdlvQf/xTY9gja0Dq3HiwQF8LaCRTXxZKRutelT44=" crossorigin="anonymous"></script>

  <script src="https://cdnjs.cloudflare.com/ajax/libs/highlight.js/9.12.0/highlight.min.js" integrity="sha256-/BfiIkHlHoVihZdc6TFuj7MmJ0TWcWsMXkeDFwhi0zw=" crossorigin="anonymous"></script>

<script src="https://cdnjs.cloudflare.com/ajax/libs/fancybox/2.1.7/js/jquery.fancybox.min.js" integrity="sha256-GEAnjcTqVP+vBp3SSc8bEDQqvWAZMiHyUSIorrWwH50=" crossorigin="anonymous"></script>


<script src="https://ifence.gitee.io/js/script-pcw6v3xilnxydl1vddzazdverrnn9ctynvnxgwho987mfyqkuylcb1nlt.min.js"></script>


<script lang="javascript">
window.onload = updateMinWidth;
window.onresize = updateMinWidth;
document.getElementById("sidebar").addEventListener("transitionend", updateMinWidth);
function updateMinWidth() {
  var sidebar = document.getElementById("sidebar");
  var main = document.getElementById("main");
  main.style.minWidth = "";
  var w1 = getComputedStyle(main).getPropertyValue("min-width");
  var w2 = getComputedStyle(sidebar).getPropertyValue("width");
  var w3 = getComputedStyle(sidebar).getPropertyValue("left");
  main.style.minWidth = `calc(${w1} - ${w2} - ${w3})`;
}
</script>

<script>
$(document).ready(function() {
  hljs.configure({ classPrefix: '', useBR: false });
  $('pre.code-highlight > code, pre > code').each(function(i, block) {
    if (!$(this).hasClass('codeblock')) {
      $(this).addClass('codeblock');
    }
    hljs.highlightBlock(block);
  });
});
</script>


  
    
      <script>
        var disqus_config = function () {
          this.page.url = 'https:\/\/ifence.gitee.io\/2019\/09\/scala%E4%B8%ADcontinue%E5%92%8Cbreak%E7%9A%84%E5%87%A0%E7%A7%8D%E5%AE%9E%E7%8E%B0%E6%96%B9%E5%BC%8F\/';
          
            this.page.identifier = '\/2019\/09\/scala%E4%B8%ADcontinue%E5%92%8Cbreak%E7%9A%84%E5%87%A0%E7%A7%8D%E5%AE%9E%E7%8E%B0%E6%96%B9%E5%BC%8F\/'
          
        };
        (function() {
          
          
          if (window.location.hostname == "localhost") {
            return;
          }
          var d = document, s = d.createElement('script');
          var disqus_shortname = 'hugo-tranquilpeak-theme';
          s.src = '//' + disqus_shortname + '.disqus.com/embed.js';

          s.setAttribute('data-timestamp', +new Date());
          (d.head || d.body).appendChild(s);
        })();
      </script>
    
  




    
  </body>
</html>

